<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getSubmission } from '@/api/questionnaire'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const router = useRouter()

const dialogVisible = ref(false)
const currentQuestionnaire = ref(null)
const currentAnswers = ref(null)

// 检查提交记录
const showSubmission = async (questionnaireId) => {
  try {
    const res = await getSubmission(questionnaireId)
    if (res.code === 200) {
      // 显示提交记录
      currentQuestionnaire.value = res.data.questionnaire
      currentAnswers.value = res.data.answers
      
      // 如果答案是字符串，尝试解析
      if (typeof res.data.answers === 'string') {
        try {
          currentAnswers.value = JSON.parse(res.data.answers)
        } catch (e) {
          console.error('答案解析失败:', e)
        }
      }
      
      dialogVisible.value = true
      return true
    }
    ElMessage.warning('未找到提交记录')
    return false
  } catch (error) {
    console.error('加载提交记录失败:', error)
    ElMessage.error('加载提交记录失败')
    return false
  }
}

// 处理填写问卷
const handleFill = async (questionnaire) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再填写问卷')
    router.push({
      path: '/login',
      query: { redirect: `/questionnaire/submit/${questionnaire.id}` }
    })
    return
  }

  // 如果已提交，显示提交记录
  if (questionnaireStore.isSubmitted(questionnaire.id)) {
    await showSubmission(questionnaire.id)
  } else {
    // 未提交，跳转到填写页面
    router.push(`/questionnaire/submit/${questionnaire.id}`)
  }
}

// 计算属性：解析答案
const parsedAnswers = computed(() => {
  if (!currentAnswers.value) return []
  try {
    // 解析答案
    const answersObj = typeof currentAnswers.value === 'string' 
      ? JSON.parse(currentAnswers.value) 
      : currentAnswers.value
      
    // 处理不同的答案格式
    let normalizedAnswers = answersObj.answers || answersObj
    
    // 获取问卷中的问题
    const questions = currentQuestionnaire.value?.questions || []

    return questions.map(question => {
      const answer = normalizedAnswers[question.id]
      return {
        question: question.title,
        answer: Array.isArray(answer) ? answer : answer ? [answer] : ['未作答']
      }
    })
  } catch (e) {
    console.error('解析答案失败:', e, currentAnswers.value)
    return []
  }
})
</script>

<template>
  <div class="questionnaire-list">
    <!-- ... 其他内容 ... -->

    <!-- 答案详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="提交记录"
      width="50%"
    >
      <div v-if="currentQuestionnaire">
        <h3>{{ currentQuestionnaire.title }}</h3>
        <div class="description" v-if="currentQuestionnaire.description">
          {{ currentQuestionnaire.description }}
        </div>
        <div v-for="(item, index) in parsedAnswers" :key="index" class="answer-item">
          <div class="question">{{ item.question }}</div>
          <div class="answer">
            <el-tag 
              v-for="(answer, i) in item.answer" 
              :key="i"
              class="answer-tag"
            >
              {{ answer }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template> 